<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clearList"
    />
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        :label="$t('message.xyxm')"
        min-width="100"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.xyzjh')"
        min-width="160"
        prop="idCard"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.rlzp')"
        min-width="80"
        prop="showAvatar"
        show-overflow-tooltip
      >
        <!-- 人脸照片学员管理 -->
        <template slot-scope="scope">
          <el-image
            shape="circle"
            style="width: 40px; height: 40px"
            fit="cover"
            class="flex-cc"
            :src="
              scope.row.showAvatar
                ? scope.row.showAvatar
                : scope.row.showAvatar
                ? scope.row.showAvatar
                : default_pic
            "
            :preview-src-list="[
              scope.row.showAvatar
                ? scope.row.showAvatar
                : scope.row.showAvatar
                ? scope.row.showAvatar
                : default_pic
            ]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture" />
            </div>
          </el-image>
        </template>
        <!-- <template slot-scope="scope">
          <div class="rlPhoto" style="width:40px;height: 40px;">
            <img v-if="scope.row.showAvatar" :src="scope.row.showAvatar" alt="">
            <span v-else>-</span>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.sex')"
        min-width="60"
        prop="sex"
      >
        <template v-slot="scope">
          <span v-if="scope.row.sex == '1'">{{ $t('message.nan') }}</span>
          <span v-if="scope.row.sex == '2'">{{ $t('message.nv') }}</span>
          <span v-if="scope.row.sex == '0'">{{ $t('message.bm') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.csrq')"
        prop="birthday"
        min-width="120"
      />
      <el-table-column
        align="center"
        :label="$t('message.memberInfo')"
        prop="memberInfo"
        min-width="250"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.createTime')"
        prop="createTime"
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH' ? 160 : 280"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="meta.indexOf('StudentAdd') > -1"
              type="text"
              @click="editStudent(scope.row)"
              >{{ $t('message.bjxy') }}</el-button
            >
            <el-button
              v-if="meta.indexOf('courseListByStudent') > -1"
              type="text"
              @click="rowClickDetial(scope.row)"
              >{{ $t('message.ckkc') }}</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Paginations
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />

    <el-dialog
      :title="$t('message.bjxy')"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showStudent"
    >
      <el-form
        ref="formStudent"
        :model="formStudent"
        label-width="auto"
        :rules="ruleb"
        label-suffix="："
      >
        <el-form-item prop="name" :label="$t('message.xyxm')">
          <el-input
            v-model="formStudent.name"
            maxlength="50"
            :placeholder="$t('message.qsr') + $t('message.xyxm')"
            clearable
          />
        </el-form-item>
        <el-form-item prop="sex" :label="$t('message.xyxb')">
          <el-select
            v-model="formStudent.sex"
            style="width: 100%"
            :placeholder="$t('message.qxz') + $t('message.sex')"
          >
            <el-option value="1" :label="$t('message.nan')" />
            <el-option value="2" :label="$t('message.nv')" />
            <el-option value="0" :label="$t('message.bm')" />
          </el-select>
        </el-form-item>
        <el-form-item prop="birthday" :label="$t('message.csrq')">
          <el-date-picker
            v-model="formStudent.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            :placeholder="$t('message.qxz') + $t('message.csrq')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="idCard" :label="$t('message.sfzh')">
          <el-input
            v-model="formStudent.idCard2"
            maxlength="18"
            :placeholder="$t('message.qsr') + $t('message.xysfzh')"
            clearable
          />
        </el-form-item>
        <!-- 添加人脸照片 -->
        <el-form-item :label="$t('message.rlcj')" prop="showAvatar">
          <div class="df_ac">
            <div class="img_warp">
              <img
                :src="formStudent.showAvatar ? formStudent.showAvatar : faceimg"
                class="mr20"
                style="width: 80px; height: 80px"
                alt=""
              />
              <div v-show="formStudent.showAvatar" class="delete pointer">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
            <el-button
              :loading="caijiLoading"
              type="primary"
              @click="acquisitionFace"
              >{{ $t('message.caji') }}</el-button
            >
            <el-button
              type="primary"
              icon="el-icon-camera"
              class="mr10"
              @click="openCamera"
              >{{ $t('message.pashi') }}</el-button
            >
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <el-button type="primary" icon="el-icon-upload2">{{
                $t('message.upload')
              }}</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <!-- 添加人脸照片 -->
      </el-form>
      <transition name="fade">
        <Cropper
          v-if="dialogCropperVisible"
          :option-img="optionImg"
          :fileinfo="fileinfo"
          use-type="MEMBER_IMG"
          :fixed-number="[500, 500]"
          @formSubmit="cropperSubmit"
          @formClose="cropperClose"
        />
      </transition>
      <el-dialog
        :title="$t('message.pashi')"
        :visible.sync="paisheModal"
        width="760px"
        :close-on-click-modal="modalDialog"
        :close-on-press-escape="modalDialog"
        append-to-body
        @close="closeCamera"
      >
        <video
          v-show="isShowCamera"
          id="videoCamera"
          :width="videoWidth"
          :height="videoHeight"
        />
        <canvas
          v-show="!isShowCamera"
          id="canvasCamera"
          style="display: none"
          :width="videoWidth"
          :height="videoHeight"
        />
        <span slot="footer">
          <div>
            <el-button @click="closeCamera">{{ $t('message.qx') }}</el-button>
            <el-button
              v-show="blobFileCamera"
              type="primary"
              @click="resetCamera"
              >{{ $t('message.chonpa') }}</el-button
            >
            <el-button
              v-show="blobFileCamera"
              :loading="cameraLoading"
              type="primary"
              @click="enterCamera"
              >{{ $t('message.ksjc') }}</el-button
            >
            <el-button
              v-show="!blobFileCamera"
              type="primary"
              @click="setImage"
              >{{ $t('message.pashi') }}</el-button
            >
          </div>
        </span>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showStudent = false">{{
          $t('message.qx')
        }}</el-button>
        <el-button
          v-preventReClick
          :loading="studentLoading"
          type="primary"
          @click="onSubmitb"
          >{{ $t('message.qr') }}</el-button
        >
      </div>
    </el-dialog>
    <Detail
      v-if="isShowDetail"
      ref="DetailRef"
      :meta="meta"
      @close="isShowDetail = false"
    />
    <CropperCopy
      v-if="isShowCropper"
      :option-img="blobFileCamera"
      use-type="MEMBER_IMG"
      :fixed-number="[500, 500]"
      @formSubmit="cropperSubmit"
      @formClose="cropperCameraClose"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import {
  studentManagers,
  kcStudentUpdate,
  collectFace,
  uploadFile
} from '@/api'
import { queryFormConfig } from './config'
import QueryForm from '@/components/QueryForm'
import Detail from './detail.vue'
import Cropper from '@/components/cropper'
import CropperCopy from './cropper.vue'
export default {
  name: 'StudentAdmin',
  components: {
    QueryForm,
    Detail,
    Cropper,
    CropperCopy
  },
  data () {
    return {
      isShowCamera: true,
      cameraLoading: false,
      videoWidth: 700,
      videoHeight: 525,
      mediaStreamCamera: '',
      blobFileCamera: '',
      paisheModal: false,
      dialogCropperVisible: false,
      caijiLoading: false,
      isShowCropper: false,
      uploadFileUrl: uploadFile,
      optionImg: '',
      fileinfo: {},
      faceimg: require('@/assets/images/default_faceid.png'),
      uploadParam: {
        folder: 'MEMBER_IMG'
      },
      ruleb: {
        name: [
          {
            required: true,
            message: this.$t('message.qsr') + this.$t('message.xyxm'),
            trigger: 'blur'
          }
        ]
      },
      // 人脸
      isShowDetail: false,
      modalDialog: this.$store.getters.dialog,
      queryFormConfig,
      meta: [],
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      filters: {},
      listLoading: true,

      showStudent: false,
      studentLoading: false,
      formStudent: {},
      ruleb: {
        name: [
          {
            required: true,
            message: this.$t('message.qsr') + this.$t('message.xyxm'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    acquisitionFace () {
      this.caijiLoading = true
      collectFace({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          shopId: localStorage.getItem('shopId')
        }
      }).then(
        res => {
          this.caijiLoading = false
          if (res.errorCode === '000000') {
            this.$set(this.formStudent, 'avatar', res.record.insertUrl)
            this.$set(this.formStudent, 'showAvatar', res.record.showUrl)
          }
        },
        () => {
          this.caijiLoading = false
        }
      )
    },
    cropperCameraClose () {
      this.isShowCropper = false
      this.blobFileCamera = ''
    },
    // cropperCameraSubmit(){
    // },
    async addFileChange (file, fileList) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit (config) {
      // preImg 完整路径  urlPre 不包含域名
      this.isShowCropper = false
      this.blobFileCamera = ''
      if (config.success) {
        this.$set(this.formStudent, 'avatar', config.insertUrl)
        this.$set(this.formStudent, 'showAvatar', config.showUrl)
        this.fileinfo = config
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose () {
      this.dialogCropperVisible = false
    },
    deleteDeviceConfigAddImage (file, fileList) {
      this.formStudent.avatar = ''
      this.formStudent.showAvatar = ''
    },
    // 打开相机
    openCamera () {
      this.paisheModal = true
      this.isShowCamera = true
      const that = this
      this.$nextTick(() => {
        var mediaOpts = { audio: false, video: true }
        navigator.mediaDevices
          .getUserMedia(mediaOpts)
          .then(function (stream) {
            that.mediaStreamCamera = stream
            const video = document.querySelector('#videoCamera')
            if ('srcObject' in video) {
              video.srcObject = stream
            } else {
              video.src =
                (window.URL && window.URL.createObjectURL(stream)) || stream
            }
            video.play()
          })
          .catch(function (err) {
            console.log(err)
          })
      })
    },
    // 重拍
    resetCamera () {
      this.isShowCamera = true
      this.blobFileCamera = ''
      this.openCamera()
    },
    // 关闭相机
    closeCamera () {
      this.mediaStreamCamera.getVideoTracks().forEach(function (track) {
        track.stop()
      })
      this.paisheModal = false
    },
    // 点击拍摄
    setImage () {
      const that = this
      that.isShowCamera = false
      const video = document.querySelector('#videoCamera')
      const canvas = document.querySelector('#canvasCamera')
      canvas
        .getContext('2d')
        .drawImage(video, 0, 0, that.videoWidth, that.videoHeight)
      this.mediaStreamCamera.getVideoTracks().forEach(function (track) {
        track.stop()
      })
      const dataurl = canvas.toDataURL('image/jpg')
      // this.blobFileCamera = that.base64ToFile(dataurl, 'camera')
      this.blobFileCamera = dataurl
    },
    // 确认拍摄
    enterCamera () {
      this.isShowCropper = true
      this.paisheModal = false
      this.isShowCamera = true
      // return false
      // const myFile = this.blobFileCamera
      // const formData = new FormData()
      // formData.append('file', myFile)
      // formData.append('folder', 'MEMBER_IMG')
      // // 文件对象
      // // 获取卡类型列表
      // // return;
      // this.cameraLoading = true
      // uploadFiles(formData)
      //   .then((res) => {
      //     this.cameraLoading = false
      //     this.$set(this.param, 'avatar', res.insertUrl)
      //     this.$set(this.param, 'showFaceUrl', res.showUrl)
      //     this.blobFileCamera = ''
      //     this.paisheModal = false
      //   })
      //   .catch((err) => {
      //     this.cameraLoading = false
      //     console.log('err', err)
      //   })
    },
    base64ToFile (base64, fileName) {
      // 将base64按照 , 进行分割 将前缀  与后续内容分隔开
      const data = base64.split(',')
      // 利用正则表达式 从前缀中获取图片的类型信息（image/png、image/jpeg、image/webp等）
      const type = data[0].match(/:(.*?);/)[1]
      // 从图片的类型信息中 获取具体的文件格式后缀（png、jpeg、webp）
      const suffix = type.split('/')[1]
      // 使用atob()对base64数据进行解码  结果是一个文件数据流 以字符串的格式输出
      const bstr = window.atob(data[1])
      // 获取解码结果字符串的长度
      let n = bstr.length
      // 根据解码结果字符串的长度创建一个等长的整形数字数组
      // 但在创建时 所有元素初始值都为 0
      const u8arr = new Uint8Array(n)
      // 将整形数组的每个元素填充为解码结果字符串对应位置字符的UTF-16 编码单元
      while (n--) {
        // charCodeAt()：获取给定索引处字符对应的 UTF-16 代码单元
        u8arr[n] = bstr.charCodeAt(n)
      }
      // 利用构造函数创建File文件对象
      // new File(bits, name, options)
      const file = new File([u8arr], `${fileName}.${suffix}`, {
        type: type
      })
      // 将File文件对象返回给方法的调用者
      return file
    },
    handleSizeChange (value) {
      this.pagination.rows = value
      this.getList(1)
    },
    clearList () {
      this.filters = {}
      this.getList(1)
    },
    getList (page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      studentManagers({ pagination, param: { venueId, ...filters } })
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    editStudent (row) {
      const obj = { ...row }
      if (obj.birthday) {
        obj.birthday = obj.birthday.slice(0, 10)
      }
      this.formStudent = obj
      this.showStudent = true
    },
    rowClickDetial (row) {
      this.isShowDetail = true
      this.$nextTick(() => {
        this.$refs.DetailRef.isShowDrawer = true
        this.$refs.DetailRef.detail = { ...row }
        this.$refs.DetailRef.getList()
      })
    },
    onSubmitb () {
      this.$refs.formStudent.validate(valid => {
        if (valid) {
          const param = { ...this.formStudent }
          if (param.birthday) {
            param.birthday = param.birthday + ' 00:00:00'
          }
          if (param.idCard2) {
            param.idCard = param.idCard2
          }
          this.studentLoading = true
          kcStudentUpdate({
            param
          })
            .then(res => {
              this.studentLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.xgcg'))
                this.showStudent = false
                this.getList()
              }
            })
            .catch(err => {
              this.studentLoading = false
              console.log(err)
            })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.img_warp {
  display: flex;
  justify-items: center;
  align-items: center;
  position: relative;
  width: 80px;
  height: 80px;
  margin-right: 20px;
  .delete {
    background-color: rgba(0, 0, 0, 0.5);
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: none;
    align-items: center;
    justify-content: center;
    .icon {
      color: #fff;
    }
  }
  &:hover {
    .delete {
      display: flex;
    }
  }
}
.rlPhoto {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  margin: auto;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
